package cn.sinata.wanglin.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.JsonObject;
import com.hyphenate.easeui.utils.EaseSmileUtils;
import com.xilada.xldutils.activitys.BaseActivity;
import com.xilada.xldutils.adapter.BaseRecyclerAdapter;
import com.xilada.xldutils.adapter.DividerGridItemDecoration;
import com.xilada.xldutils.adapter.HFRecyclerAdapter;
import com.xilada.xldutils.adapter.util.ViewHolder;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.DensityUtil;
import com.xilada.xldutils.utils.DialogUtils;
import com.xilada.xldutils.utils.SharedPreferencesUtils;

import java.util.List;

import cn.sinata.wanglin.R;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.model.ImgBean;
import cn.sinata.wanglin.model.LikeData;
import cn.sinata.wanglin.model.SameCityInfo;
import cn.sinata.wanglin.net.HttpManager;
import cn.sinata.wanglin.net.model.util.ResultDataSubscriber;
import cn.sinata.wanglin.utils.ExpUtils;
import cn.sinata.wanglin.utils.RelativeDateFormat;
import cn.sinata.wanglin.village.activity.AllUserInfoActivity;
import cn.sinata.wanglin.village.activity.EditCommentOtherActivity;
import cn.sinata.wanglin.village.activity.MakecomplaintsdetailActivity;
/**
 *  小区--同城八卦中的数据装载体
 * Created by liaoxiang on 16/6/20.
 */
public class SameCityListAdapter extends HFRecyclerAdapter<SameCityInfo> {
    private String userId;
    Context  mContext;
    private int imgwith=80;
    private Fragment fragment;
    private DividerGridItemDecoration mDividerGridItemDecoration;
    public SameCityListAdapter(List<SameCityInfo> mData, Context mContext, Fragment fragment) {
        super(mData, R.layout.item_makecomplaints);
        this.mContext=mContext;
        imgwith=(DensityUtil.getDeviceWidth(mContext)-DensityUtil.dip2px(mContext,30))/3;
        mDividerGridItemDecoration=new DividerGridItemDecoration(mContext);
        userId = SharedPreferencesUtils.getString(Constant.SP_USERID);
        this.fragment=fragment;
    }

    @Override
    public void onBind(final int position, final SameCityInfo data, final ViewHolder holder) {
        if (!TextUtils.isEmpty(data.getIsanonymity())) {
            if ("1".equals(data.getIsanonymity())) {
                ((SimpleDraweeView) holder.bind(R.id.iv_headview)).setImageURI(Uri.parse("res://mipmap/" + R.mipmap.ic_isanonymity));
            } else {
                ((SimpleDraweeView) holder.bind(R.id.iv_headview)).setImageURI(data.getHeadUrl());
            }
        } else {
            ((SimpleDraweeView) holder.bind(R.id.iv_headview)).setImageURI(data.getHeadUrl());
        }
        //当前用户是否点赞 1：点过 0：没点
        if(!TextUtils.isEmpty(data.getClickPraise())&&"1".equals(data.getClickPraise())){
            Resources res = mContext.getResources();
            Drawable img_off = res.getDrawable(R.mipmap.ic_zannum2);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            ((TextView)holder.bind(R.id.tv_zannum)).setCompoundDrawables(img_off, null, null, null); //设置右图标
            ((TextView)holder.bind(R.id.tv_zannum)).setTextColor(mContext.getResources().getColor(R.color.app_theme_color));
        }else{
            Resources res = mContext.getResources();
            Drawable img_off = res.getDrawable(R.mipmap.ic_zannum1);
            // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
            img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
            ((TextView)holder.bind(R.id.tv_zannum)).setCompoundDrawables(img_off, null, null, null); //设置右图标
            ((TextView)holder.bind(R.id.tv_zannum)).setTextColor(mContext.getResources().getColor(R.color.textColor66));

        }
           if(!TextUtils.isEmpty(data.getName())){
               holder.setText(R.id.tv_username,data.getName());
           }else{
            holder.setText(R.id.tv_username,Constant.DEFULT_NICKNAME);
           }
        switch (ExpUtils.getExpValue(data.getExp())){

            case 1:
                Resources res1 = mContext.getResources();
                Drawable img_off1 = res1.getDrawable(R.mipmap.ic_exp1);
                img_off1.setBounds(0, 0, img_off1.getMinimumWidth(), img_off1.getMinimumHeight());
                ((TextView)holder.bind(R.id.tv_username)).setCompoundDrawables(null, null, img_off1, null); //设置右图标
                break;
            case 2:
                Resources res2 = mContext.getResources();
                Drawable img_off2 = res2.getDrawable(R.mipmap.ic_exp2);
                img_off2.setBounds(0, 0, img_off2.getMinimumWidth(), img_off2.getMinimumHeight());
                ((TextView)holder.bind(R.id.tv_username)).setCompoundDrawables(null, null, img_off2, null); //设置右图标
                break;
            case 3:
                Resources res3 = mContext.getResources();
                Drawable img_off3 = res3.getDrawable(R.mipmap.ic_exp3);
                img_off3.setBounds(0, 0, img_off3.getMinimumWidth(), img_off3.getMinimumHeight());
                ((TextView)holder.bind(R.id.tv_username)).setCompoundDrawables(null, null, img_off3, null); //设置右图标
                break;
            case 4:
                Resources res4 = mContext.getResources();
                Drawable img_off4 = res4.getDrawable(R.mipmap.ic_exp4);
                img_off4.setBounds(0, 0, img_off4.getMinimumWidth(), img_off4.getMinimumHeight());
                ((TextView)holder.bind(R.id.tv_username)).setCompoundDrawables(null, null, img_off4, null); //设置右图标
                break;
            case 5:
                Resources res5 = mContext.getResources();
                Drawable img_off5 = res5.getDrawable(R.mipmap.ic_exp5);
                img_off5.setBounds(0, 0, img_off5.getMinimumWidth(), img_off5.getMinimumHeight());
                ((TextView)holder.bind(R.id.tv_username)).setCompoundDrawables(null, null, img_off5, null); //设置右图标
                break;
            case 6:
                Resources res6 = mContext.getResources();
                Drawable img_off6 = res6.getDrawable(R.mipmap.ic_exp6);
                img_off6.setBounds(0, 0, img_off6.getMinimumWidth(), img_off6.getMinimumHeight());
                ((TextView)holder.bind(R.id.tv_username)).setCompoundDrawables(null, null, img_off6, null); //设置右图标
                break;
        }
           if(!TextUtils.isEmpty(data.getIndustry())){
              holder.setText(R.id.tv_industry,data.getIndustry());
           }else{
                holder.setText(R.id.tv_industry,"暂无");
            }

        if(!TextUtils.isEmpty(data.getBelongLabel())){
            holder.setText(R.id.tv_lable,data.getBelongLabel());
        }else{
            holder.setText(R.id.tv_lable,"暂无");
        }
        if(!TextUtils.isEmpty(data.getCreateDate())){
            holder.setText(R.id.tv_time, RelativeDateFormat.format(data.getCreateDate()));
        }else{
            holder.setText(R.id.tv_time,"");
        }
        if("1".equals(data.getIsOneself())){
            //是否是本用户发布的 1：是 0：不是
            holder.bind(R.id.tv_delete).setVisibility(View.VISIBLE);
        }else{
            holder.bind(R.id.tv_delete).setVisibility(View.GONE);
        }
        if(!TextUtils.isEmpty(data.getContent())){
            ((TextView) holder.bind(R.id.tv_content)).setText(EaseSmileUtils.getSmiledText(mContext,data.getContent()));
        }else{
            holder.setText(R.id.tv_content,"暂无发布内容");
        }
        //浏览量
        if(!TextUtils.isEmpty(data.getBrowses())){
            holder.setText(R.id.tv_seenum,data.getBrowses());
        }else{
            holder.setText(R.id.tv_seenum,"0");
        }
        //评论量
        if(!TextUtils.isEmpty(data.getCommentCount())){
            if(Integer.parseInt(data.getCommentCount())>2){
                holder.bind(R.id.tv_morecomment).setVisibility(View.VISIBLE);
            }else{
                holder.bind(R.id.tv_morecomment).setVisibility(View.GONE);
            }
            holder.setText(R.id.tv_commentnum,data.getCommentCount());
        }else{
            holder.bind(R.id.tv_morecomment).setVisibility(View.GONE);
            holder.setText(R.id.tv_commentnum,"0");
        }
        //点赞量
        if(!TextUtils.isEmpty(data.getLikes())){
            holder.setText(R.id.tv_zannum,data.getLikes());
        }else{
            holder.setText(R.id.tv_zannum,"0");
        }
        //评论1
        if(!TextUtils.isEmpty(data.getName1())){
            String commentPerson=data.getName1()+":";
            String allcomment=commentPerson+data.getComment1();
            StyleSpan boldSpan=new StyleSpan(Typeface.BOLD);
            SpannableStringBuilder builder = new SpannableStringBuilder(allcomment);
            builder.setSpan(boldSpan,0,commentPerson.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

            Spannable span = EaseSmileUtils.getSmiledText(mContext,builder);
            ((TextView)holder.bind(R.id.tv_commentshow1)).setText(span, TextView.BufferType.SPANNABLE);
            holder.bind(R.id.tv_commentshow1).setVisibility(View.VISIBLE);
            holder.bind(R.id.ly_comment).setVisibility(View.VISIBLE);
            holder.bind(R.id.iv_comment_boxtop).setVisibility(View.VISIBLE);
        }else{
            holder.setText(R.id.tv_commentshow1,"");
            holder.bind(R.id.tv_commentshow1).setVisibility(View.GONE);
            holder.bind(R.id.ly_comment).setVisibility(View.GONE);
            holder.bind(R.id.iv_comment_boxtop).setVisibility(View.GONE);
        }
        //评论2
        if(!TextUtils.isEmpty(data.getName2())){
            String commentPerson=data.getName2()+":";
            String allcomment=commentPerson+data.getComment2();
            StyleSpan boldSpan=new StyleSpan(Typeface.BOLD);
            SpannableStringBuilder builder = new SpannableStringBuilder(allcomment);
            builder.setSpan(boldSpan,0,commentPerson.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);

            Spannable span = EaseSmileUtils.getSmiledText(mContext,builder);
            ((TextView)holder.bind(R.id.tv_commentshow2)).setText(span, TextView.BufferType.SPANNABLE);
            holder.bind(R.id.tv_commentshow2).setVisibility(View.VISIBLE);

        }else{
            holder.setText(R.id.tv_commentshow2,"");
            holder.bind(R.id.tv_commentshow2).setVisibility(View.GONE);

        }
            GridLayoutManager mgr=new GridLayoutManager(mContext,3);
            RecyclerView rv_showphoto=(RecyclerView)holder.bind(R.id.rv_showphoto);
            rv_showphoto .setLayoutManager(mgr);
            rv_showphoto.removeItemDecoration(mDividerGridItemDecoration);
            rv_showphoto.addItemDecoration(mDividerGridItemDecoration);
            BaseRecyclerAdapter   showphotoAdapter=new BaseRecyclerAdapter<ImgBean>(data.getImg(),R.layout.item_showphoto) {
                @Override
                public void onBind(final int position, final ImgBean imgBean, ViewHolder holder) {
                    if(data.getImg().size()!=1){
                        holder.bind(R.id.iv_showphoto).getLayoutParams().width=imgwith;
                        holder.bind(R.id.iv_showphoto).getLayoutParams().height=imgwith;
                        ((SimpleDraweeView) holder.bind(R.id.iv_showphoto)).setImageURI(imgBean.getImgUrl());
                    }else{
                        holder.bind(R.id.iv_showphoto).getLayoutParams().width=imgwith*2;
                        holder.bind(R.id.iv_showphoto).getLayoutParams().height=imgwith*2;
                        ((SimpleDraweeView) holder.bind(R.id.iv_showphoto)).setImageURI(imgBean.getImgUrl());
                    }
                }
            };
            showphotoAdapter.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(View view, int position) {
                    ActivityUtil.create(mContext).go(MakecomplaintsdetailActivity.class)
                            .put("type","2")
                            .put("id",data.getId())
                            .start();
                }
            });
            rv_showphoto.setAdapter(showphotoAdapter);
        holder.bind(R.id.tv_commentnum).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtil.create(fragment)
                        .go(EditCommentOtherActivity.class)
                        .put("id",data.getId())
                        .put("toUser","-1")
                        .put("externalType","A")
                        .startForResult(12);
            }
        });
        holder.bind(R.id.tv_content).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtil.create(mContext).go(MakecomplaintsdetailActivity.class)
                        .put("type","2")
                        .put("id",data.getId())
                        .start();
            }
        });
        holder.bind(R.id.tv_morecomment).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                ActivityUtil.create(mContext).go(MakecomplaintsdetailActivity.class)
                        .put("type","2")
                        .put("id",data.getId())
                        .start();
            }
        });
        holder.bind(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogUtils.createNoticeDialog(mContext, "请注意", "您确定要删除当前信息么？", "确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        delSpoke(position,data.getId());
                    }
                });

            }
        });
        holder.bind(R.id.tv_zannum).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                praise(position,data.getId(),holder);
            }
        });
        holder.bind(R.id.iv_headview).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if("1".equals(data.getIsanonymity())){
                    return;
                }
//                是否是好友(0：不是好友，1:已经是好友，2：待同意)
                ActivityUtil.create(mContext).go(AllUserInfoActivity.class).put("friendID",data.getUserId())
                        .start();


            }
        });
    }
    private void delSpoke(final int position, String id){
        BaseActivity activity = null;
        if (mContext instanceof BaseActivity) {
            activity = (BaseActivity) mContext;
            activity.showDialog();
        }
        HttpManager.delSpoke(id,"A")
                .subscribe(new ResultDataSubscriber<JsonObject>(activity) {
                    @Override
                    public void onSuccess(String msg, JsonObject jsonObject) {
                        mData.remove(position);
                        notifyDataSetChanged();
                    }
                });
    }
    private void praise(final int position, String id, final ViewHolder holder){
        BaseActivity activity = null;
        if (mContext instanceof BaseActivity) {
            activity = (BaseActivity) mContext;
            activity.showDialog();
        }

        HttpManager.clickPraise(userId,"A",id)
                .subscribe(new ResultDataSubscriber<LikeData>(activity) {
                    @Override
                    public void onSuccess(String msg, LikeData likeData) {
                        showToast(msg);
                        int num= Integer.parseInt(mData.get(position).getLikes());
                        //当前用户行为 1：取消点赞 0：点赞
                        if (likeData.getClickPraise() == 0) {
                            num++;
                            mData.get(position).setClickPraise("1");
                            mData.get(position).setLikes(""+num);
                        } else {
                            num--;
                            mData.get(position).setClickPraise("0");
                            mData.get(position).setLikes(""+num);
                        }
                        notifyDataSetChanged();
                    }
                });
    }
}
